package com.hhl.order.service.impl;

import java.util.Date;
import java.util.Objects;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.codingapi.txlcn.common.util.Transactions;
import com.codingapi.txlcn.tracing.TracingContext;
import com.hhl.common.db.domain.Demo;
import com.hhl.common.spring.ServiceAccountClient;
import com.hhl.common.spring.ServiceStorageClient;
import com.hhl.order.mapper.Orderapper;
import com.hhl.order.service.OrderService;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
	@Autowired
    private Orderapper orderapper;

    @Autowired
    private ServiceAccountClient serviceAccountClient;
    @Autowired
    private ServiceStorageClient serviceStorageClient;
    @Autowired
    private RestTemplate restTemplate;

//    @Autowired
//    public OrderServiceImpl(Orderapper orderapper, ServiceAccountClient serviceAccountClient, ServiceStorageClient serviceStorageClient, RestTemplate restTemplate) {
//        this.orderapper = orderapper;
//        this.serviceAccountClient = serviceAccountClient;
//        this.serviceStorageClient = serviceStorageClient;
//        this.restTemplate = restTemplate;
//    }

    //AOP方式声明分布式事务示例   AopTypeDTXConfiguration,account, storage 用的注解方式
    @Override
    public String execute(String value, String exFlag) {
        // step1. call remote ServiceD
        String dResp = serviceAccountClient.rpc(value);
//        String dResp = restTemplate.getForObject("http://127.0.0.1:12002/rpc?value=" + value, String.class);


        // step2. call remote ServiceE
        String eResp = serviceStorageClient.rpc(value);

        // step3. execute local transaction
        Demo demo = new Demo();
        demo.setGroupId(TracingContext.tracing().groupId());
        demo.setDemoField(value);
        demo.setCreateTime(new Date());
        demo.setAppName(Transactions.getApplicationId());
        orderapper.save(demo);

        int i = 1/0;
        //如果这里异常，storage使用TCC模式。storage的事务不会回滚。将TCC改为TXC/LCN，则会回滚，不清楚怎么回事
        
        
        // 置异常标志，DTX 回滚
        if (Objects.nonNull(exFlag)) {
            throw new IllegalStateException("by exFlag");
        }

        return dResp + " > " + eResp + " > " + "ok-service-a";
    }
}
